from typing import Dict, Any
from .Exporter import Exporter
import re

class LuaExporter(Exporter):
    def compile_key(self, key):
        key_type = type(key)
        if key_type != str:
            return f"[{key}]"

        # 字符串 key
        if re.match(r'^[_a-zA-Z_]*$', key):
            return key

        return f'["{key}"]'

    def compile_value(self, value):
        value_type = type(value)
        if value_type == str:
            if re.match(r'^\[+', value) or re.search(r'\]$', value):
                return f"[=[{value}]=]"
            return f"[[{value}]]"
        elif value_type == bool:
            if value is True:
                return "true"
            elif value is False:
                return "false"
            else:
                raise ValueError(f"解析错误，bool值应该为True或False，但是解析出了: {value}")
        elif value_type == int:
            return f"{value}"
        elif value_type == float:
            return f"{value}"
        elif value_type == list:
            ret_str = "{"
            is_first = True
            for i in range(len(value)):
                item = value[i]
                if is_first:
                    is_first = False
                else:
                    ret_str += ","
                ret_str += f"{self.compile_value(item)}"

            ret_str += "}"
            return ret_str
        elif value_type == dict:
            return self.compile_object(value)

        return value

    def compile_object(self, obj: Dict[str, Any]):
        ret_str = "{"
        is_first = True
        for k, v in obj.items():
            if is_first:
                is_first = False
            else:
                ret_str += ","
            ret_str += f"{self.compile_key(k)}={self.compile_value(v)}"

        ret_str += "}"
        return ret_str


    def write_output(self, data: Dict[str, Any], output_path: str, file_name: str):
        with open(output_path, 'w', encoding='utf-8') as f:
            if len(data.keys()) == 0:
                f.write('return {}')
                return

            for sheet_name, sheet_data in data.items():
                sheet_str = f"local {sheet_name}={{"
                if len(sheet_data.keys()) == 0:
                    sheet_str += "}\n"
                    f.write(sheet_str)
                    continue

                sheet_str += "\n"
                for key, row in sheet_data.items():
                    sheet_str += f"{self.compile_key(key)}={self.compile_object(row)},\n"

                sheet_str += "}\n"
                f.write(sheet_str)

            f.write("\n")
            f.write("return {\n")
            for sheet_name in data.keys():
                f.write(f"{sheet_name}={sheet_name},\n")
            f.write("}")
    
    def file_ext(self):
        return "lua"